strncmp関数は、文字列のデータを指定された長さだけ比較します。
#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n);
*s1および、*s2は比較する文字列を指定します。
nは比較する長さをバイト単位で指定します。
戻り値として、次の値を返します。
- s1がs2より小さい場合は負の値を返します。
- s1とs2が等しい場合は0を返します。
- s1がs2より大きい場合は正の値を返します。
strncmp関数の場合は、第3引数のn文字を比較しますので、比較する文字列(s1とs2)はヌル文字(’\0’)で終わっている必要はありません。
プログラム 例
#include <stdio.h>
#include <string.h>
#define SIZE 1024
int main()
{
FILE *fp;
char path[50]; /* 入力ファイルのパス名 */
char buff[SIZE];
char *start_ptr; /* 比較開始位置 */
char *end_ptr; /* 比較終了位置 */
char key[11]; /* 比較(検索)文字列 */
int search_cnt; /* 検索結果 */
int return_code = 0;
printf('検索するファイルのパス名を入力してください ==> ');
scanf('%s', path);
if ((fp = fopen(path, 'r')) != NULL) {
printf('検索する文字列を入力してください(10文字以内) ==> ');
scanf('%10s', key);
search_cnt = 0;
while (fgets(buff, SIZE, fp) != NULL) {
start_ptr = buff;
end_ptr = buff + strlen(buff);
do {
/* 文字列の比較 */
if (strncmp(start_ptr, key, strlen(key)) == 0) {
++search_cnt;
start_ptr += strlen(key);
}
else {
++start_ptr;
}
} while (start_ptr < end_ptr);
}
fclose(fp);
printf('%sは%d個ありました\n', key, search_cnt);
}
else {
printf('%sのオープンに失敗しました\n', path);
return_code = 1;
}
return return_code;
}
例の実行結果
$ cat temp_3.txt
Hello World!!.
Hi.
Hello Hello hello.
hello Hello.
Bye.
$
$ ./strncmp.exe
検索するファイルのパス名を入力してください ==> temp_3.txt
検索する文字列を入力してください(10文字以内) ==> Hello
Helloは4個ありました
$
$ ./strncmp.exe
検索するファイルのパス名を入力してください ==> temp_3.txt
検索する文字列を入力してください(10文字以内) ==> hello
helloは2個ありました
$